package com.ruoyi.app.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.$;
import com.ruoyi.app.config.ConfigureInt;
import com.ruoyi.app.config.ConfigureStr;
import com.ruoyi.app.controller.BaseController;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * Created by Zhang on 2018/8/26.
 */
@Component
@Slf4j
public  abstract class ApiLocalinterceptor extends BaseController implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getServletPath().equals("/error")){
            return true;
        }
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            return true;
        }
        String token = request.getHeader(ConfigureStr.Token.getValue());
        if(StrUtil.isEmpty(token)){
            renderJson(JSONObject.toJSONString($.error(ConfigureInt.NOTAUTH.getValue(),"请先登录")),response);
            return false;
        }
        try{
            Object o=  StpUtil.getLoginIdByToken( token);
            Long  userId=Long.parseLong(o+"");
            request.setAttribute(ConfigureStr.TokenUserId.getValue(),  userId );
        }catch ( Exception e){
            e.printStackTrace();
            renderJson(JSONObject.toJSONString($.error(ConfigureInt.LOGIN_TIME_OUT.getValue(),"登录失效，请重新登录")),response);
            return false;
        }
        return true;
    }



}
